package com.example.cnotebook;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cnotebook.pojo.NoteInfo;
import com.example.cnotebook.util.OKHttpUtil;
import com.example.cnotebook.util.PlatformUtil;
import com.example.cnotebook.util.UserConstant;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import okhttp3.Response;

public class EditNoteActivity extends BaseActivity implements View.OnClickListener, OKHttpUtil.CallBack {
    private ImageView ivBack;
    private ImageView ivPlayAudio;
    private ImageView ivStopAudio;
    private ImageView ivEdit;
    private ImageView ivShare;
    private ImageView ivDelete;
    private TextView tvTitle;
    private TextView tvContent;
    private ProgressBar progressBar;
    private File filesDir;//持久文件目录

    private int noteId;
    private NoteInfo noteInfo;
    private MediaPlayer mediaPlayer;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0x1) {
                Toast.makeText(EditNoteActivity.this, "语音下载完成", Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
                try {
                    mediaPlayer.setDataSource(filesDir + "/" + noteInfo.getAudioName());
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_note);
        noteId = getIntent().getIntExtra("nodeId", -1);
        filesDir = getFilesDir();
        initView();
        initData();
    }

    private void initData() {
        ArrayList<NoteInfo> noteInfos = UserConstant.noteInfos;
        for (NoteInfo n : noteInfos) {
            if (n.getId() == noteId) {
                noteInfo = n;
                tvTitle.setText(n.getTitle());
                tvContent.setText(n.getContent());
                break;
            }
        }
        System.out.println(noteInfo);
        if (noteInfo.getHasAudio() == 1) {
            ivPlayAudio.setVisibility(View.VISIBLE);
        } else {
            ivPlayAudio.setVisibility(View.GONE);
        }
        mediaPlayer = new MediaPlayer();
        try {
            if (checkLocalHasAudio()) {
                mediaPlayer.setDataSource(filesDir + "/" + noteInfo.getAudioName());
                mediaPlayer.prepare();
            } else {
                getAudioDateByNetwork();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //本地没有音频，去服务器获取
    private void getAudioDateByNetwork() {
        progressBar.setVisibility(View.VISIBLE);
        OKHttpUtil.downLoadAudio("/note/downLoadAudio/" + noteInfo.getAudioName(), new OKHttpUtil.CallBackDownLoad() {
            @Override
            public void onSuccess(Response response) throws JSONException {
                InputStream inputStream = response.body().byteStream();
                File filesDir = getFilesDir();
                File file = new File(filesDir + "/" + noteInfo.getAudioName());
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    byte[] b = new byte[1024];
                    int len;
                    while ((len = inputStream.read(b)) > 0) {
                        fos.write(b, 0, len);
                    }
                    handler.sendEmptyMessage(0x1);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    //查看本地是否有音频文件
    private boolean checkLocalHasAudio() {
        String s = filesDir + "/" + noteInfo.getAudioName();
        System.out.println("-----------------" + s);
        File file = new File(s);
        boolean exists = file.exists();
        System.out.println("exists-----------" + exists);
        return exists;
    }

    private void initView() {

        ivBack = findViewById(R.id.iv_back);
        ivPlayAudio = findViewById(R.id.iv_play_audio);
        ivStopAudio = findViewById(R.id.iv_stop_audio);
        ivEdit = findViewById(R.id.iv_edit);
        ivShare = findViewById(R.id.iv_share);
        ivDelete = findViewById(R.id.iv_delete);
        tvTitle = findViewById(R.id.tv_title);
        progressBar = findViewById(R.id.progressBar);
        tvContent = findViewById(R.id.tv_content);

        ivBack.setOnClickListener(this);
        ivEdit.setOnClickListener(this);
        ivDelete.setOnClickListener(this);
        ivShare.setOnClickListener(this);
        ivPlayAudio.setOnClickListener(this);
        ivStopAudio.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_edit:
                Intent intent = new Intent(this, AddNoteActivity.class);
                intent.putExtra("noteId", noteId);
                startActivity(intent);
                finish();
                break;
            case R.id.iv_share:
                PlatformUtil.shareQQ(this, tvContent.getText().toString());
                break;
            case R.id.iv_delete:
                try {
                    deleteNode();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.iv_play_audio:
                try {
                    playAudio();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.iv_stop_audio:
                ivPlayAudio.setVisibility(View.VISIBLE);
                ivStopAudio.setVisibility(View.GONE);
                mediaPlayer.pause();
                break;
        }
    }

    private void playAudio() throws IOException {
        ivPlayAudio.setVisibility(View.GONE);
        ivStopAudio.setVisibility(View.VISIBLE);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                ivPlayAudio.setVisibility(View.VISIBLE);
                ivStopAudio.setVisibility(View.GONE);
            }
        });
        mediaPlayer.start();
    }

    private void deleteNode() throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", noteId);
        jsonObject.put("isDelete", 0);
        OKHttpUtil.post("/note/update", jsonObject, this, this);
    }

    @Override
    public void onSuccess(JSONObject response) throws JSONException {
        Toast.makeText(this, "删除成功！", Toast.LENGTH_SHORT).show();
        UserConstant.userIsSaveData = true;
        UserConstant.homeIsSaveData = true;
        finish();
    }

    @Override
    public void onFailure(int errorNo, String strMsg) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}
